//*********************************************************************
// Copyright (C) 2014 Hell Prototypes / www.hellprototypes.com
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
//********************************************************************
#include <avr/io.h>
#include <avr/power.h>
#include <util/delay.h>
#include "common.h"

#define START_EXT_ADC()		setbit(ADCA.CH2.CTRL, 7)
#define WAIT_EXT_CONVERT()	do{ while(!testbit(ADCA.CH2.INTFLAGS,0)); ADCA.CH2.INTFLAGS = 1;}while(0)


void ext_adc_init()
{
	PR.PRPB  = 0x05;

	ADCA.CH2.MUXCTRL  = 0x40;	// Channel 8 input: ADC8 pin
	ADCA.CH2.CTRL	  = 0x01;	// Single-ended positive input signal

	PORTB.PIN0CTRL	  = 0x07;  //Digital input buffer disabled
}

void ext_adc_start()
{
	ADCA.CTRLB		  = 0x60;   // High current limit, signed mode, no free run, 12bit
	ADCA.REFCTRL	  = 0x02;	// REF= 1V
}

void ext_adc_stop()
{
	ADCA.REFCTRL	  = 0x12;	// REF= VCC/1.6 (3.3V/1.6 = 2.0625V)
	ADCA.CTRLB		  = 0x64;  // High current limit, signed mode, no free run, 8 bit
}

// Get extadc value
int ext_adc_get()
{
	int voltage;

	//delay_us(10);
	ms_delay(2);
	START_EXT_ADC();
	WAIT_EXT_CONVERT();
    //((ulong)ADCA.CH2.RES * 1000) / 256 - 50;//0.05*4900 = 245
	voltage = (long)ADCA.CH2.RES*1000 / 4096 - 50;

    return voltage;
}
